package org.jypj.dev.controller;

import java.io.File;
import java.util.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.jypj.dev.dao.ICountMonthDao;
import org.jypj.dev.model.UserScore;
import org.jypj.dev.util.*;
import org.jypj.dev.vo.CountVo;
import org.jypj.dev.vo.SeasonVo;
import org.jypj.dev.vo.TodayScore;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

/**
 * 统计控制器
 *
 * @author ChenYu
 */
@RequestMapping(value = "countMonthController")
@Controller
public class CountMonthController {


    @Resource
    private ICountMonthDao countMonthDao;

    /**
     * 跳转到日常分析总结页面
     *
     * @return
     */
    @RequestMapping(value = "toCountMonthAnalyze.action")
    public String toCountMonthAnalyze(HttpServletRequest request) {
        String pattern = "yyyy-MM-dd";
        String todayStr = DateUtils.getYestodayString2(pattern);
        String sevenDayBefore = DateUtils.getSomeDayString(todayStr, pattern, -7);
        request.setAttribute("startDate", sevenDayBefore);
        request.setAttribute("endDate", todayStr);
        return "back/count/count_month_analyze";
    }

    /**
     * 跳转到日常分析总结页面
     *
     * @return
     */
    @RequestMapping(value = "toCountMonthUserScore.action")
    public String toCountMonthUserScore(HttpServletRequest request) {
        String pattern = "yyyy-MM";
        String todayStr = DateUtils.getTodayString2(pattern);
        request.setAttribute("startDate", todayStr);
        return "back/count/count_month_user_score";
    }

    /**
     * 查询所有用户分数
     *
     * @param planMonth
     * @return
     */
    @RequestMapping(value = "selectAllUserScore.action")
    @ResponseBody
    public Map<String, Object> selectAllUserScore(String startDate, String searchKey, HttpSession session) {
        Map<String, Object> dataMap = new HashMap<>();
        int code = 0;
        Map<String, Object> queryMap = new HashMap<>();
        try {
            queryMap.put("planMonth", startDate);
            queryMap.put("searchKey", searchKey);
            List<UserScore> userScores = countMonthDao.selectAllUserScoreByMonth(queryMap);
            session.setAttribute("userScores", userScores);
            dataMap.put("data", userScores);
        } catch (Exception e) {
            code = -1;
        }
        dataMap.put("code", code);
        return dataMap;
    }

    /**
     * 导出所有用户分数excel
     *
     * @param startDate
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "exportExcelAllUserScore.action")
    public void exportExcelAllUserScore(String startDate, HttpSession session, HttpServletResponse response) {
        List<UserScore> userScores = (List<UserScore>) session.getAttribute("userScores");
        if (userScores != null && userScores.size() > 0) {
            exportExcel(userScores, startDate, session, response);
        }
    }

    /**
     * 导出excel
     *
     * @param userScores
     * @param startDate
     * @param session
     * @param response
     */
    public void exportExcel(List<UserScore> userScores, String startDate, HttpSession session,
                            HttpServletResponse response) {

        WritableWorkbook workbook_temp = null;// Excel数据组装
        String usersTempPath = session.getServletContext().getRealPath("/static/excelModel/") + File.separator
                + "countMonthScore_temp.xls";
        String userPath = session.getServletContext().getRealPath("/static/excelModel/") + File.separator
                + "countMonthScore.xls";
        Workbook workbook = null; // 工作表
        try {
            workbook = Workbook.getWorkbook(new File(userPath)); // 创建一张工作表从实体路径下
            workbook_temp = Workbook.createWorkbook(new File(usersTempPath), workbook); // 拷贝一份模板
            WritableSheet sheet = workbook_temp.getSheet(0);
            sheet.addCell(new Label(0, 0, startDate + " 随车机械师月平均得分统计表"));
            for (int i = 0; i < userScores.size(); i++) {
                UserScore userScore = userScores.get(i);
                sheet.addCell(new Label(0, 3 + i, i + 1 + ""));
                sheet.addCell(new Label(1, 3 + i, userScore.getUserNum()));
                sheet.addCell(new Label(2, 3 + i, userScore.getUserName()));
                sheet.addCell(new Label(3, 3 + i, userScore.getScore() + ""));
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            // 关闭Excel工作薄对象
            if (workbook_temp != null) {
                try {
                    workbook_temp.write();
                    workbook_temp.close();
                    ExcelHelper.outputExcel(response, startDate + " 随车机械师月平均得分统计表", usersTempPath);
                    new File(usersTempPath).delete();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
            if (workbook != null) {
                workbook.close();
            }
        }

    }

    /**
     * 月季年显示 <7天以天显示，31-180 以月份显示 181-731 以季度显示 >731以年份显示 但必须保证是搜索是在同一年之内
     *
     * @param startDate "2017-02-21"
     * @param endDate   "2017-02-28"
     * @return
     */
    @RequestMapping("selectDateSpanScore.action")
    @ResponseBody
    public Map<String, Object> selectDateSpanScore(String startDate, String endDate,HttpSession session) {
        Map<String, Object> datas = (Map<String, Object>) session.getAttribute(startDate+"-"+endDate+"datas");
        if(datas!=null){
            return datas;
        }
        Map<String, Object> dataMap = new HashMap<>();
        String startYear = startDate.substring(0, 4);
        String endYear = endDate.substring(0, 4);
        int dateDayOffset = DateUtils.getDateDayOffset(endDate, startDate);
        int code = 0;
        if (dateDayOffset < 7) {
            code = -2;//保证天数至少为7天
            dataMap.put("code", code);
            return dataMap;
        }
        String[] dateStrs = null;
        //以天显示
        if (7 <= dateDayOffset && dateDayOffset <= 31) {
            dateStrs = DateUtils.getEveryDateStrFromDateSpan(startDate, endDate);
        } else if (31 < dateDayOffset && dateDayOffset <= 180) {//以月份显示
            dateStrs = DateUtils.getEveryMonthStrFromDateSpan(startDate, endDate);
        } else if (180 < dateDayOffset && dateDayOffset < 731) {//季度显示
            String[] monStrs = DateUtils.getEveryMonthStrFromDateSpan(startDate, endDate);
            Set<SeasonVo> seasonVos = new LinkedHashSet<>();
            for (String month : monStrs) {
                SeasonVo seasonVo = DateUtils.getSeasonFromMonth(month);
                seasonVos.add(seasonVo);
            }
            dateStrs = new String[seasonVos.size()];
            int i = 0;
            for (SeasonVo s : seasonVos) {
                dateStrs[i] = s.getYearStr() + s.getName();
                i++;
                Map<String, String> queryMap = DateUtils.getMonthSpanFromSeason(s);
            }
        } else if (dateDayOffset > 731) {//年份显示
            dateStrs = DateUtils.getYearSpanFromDateSpan(startDate, endDate);
        }
        int[] scores = new int[dateStrs.length];
        for (int i = 0; i < dateStrs.length; i++) {
            scores[i] = new Random().nextInt(20) + 50;
        }
        dataMap.put("code", code);
        dataMap.put("dateStrs", dateStrs);
        dataMap.put("scores", scores);
        session.setAttribute(startDate+"-"+endDate+"datas",dataMap);
        return dataMap;
    }

    /**
     * 查询时间段的平均分数
     *
     * @param startDate
     * @param endDate
     * @return
     */
    @RequestMapping("selectDateSpanAvgScore.action")
    @ResponseBody
    public Map<String, Object> selectDateSpanAvgScore(String startDate, String endDate,HttpSession session) {
        Map<String, Object> dataMap = new HashMap<>();
        TodayScore ts1 = (TodayScore) session.getAttribute(startDate+"-"+endDate+"datas1");
        if(ts1!=null){
            dataMap.put("data",ts1);
            return dataMap;
        }
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("startDate",startDate);
        queryMap.put("endDate",endDate);
        TodayScore ts = new TodayScore();
        List<CountVo> countVos = countMonthDao.selectScoreSpan(queryMap);
        UserScoreUtil.getUserNumAndSetScoreSpan(countVos,ts);
        UserScore us1 = countMonthDao.selectMaxScoreUser(queryMap);
        UserScore us2 = countMonthDao.selectMinScoreUser(queryMap);
        if(us1!=null){
            ts.setMaxScore(us1.getScore());
            ts.setMaxScoreUser(us1.getUserName());
        }else{
            ts.setMaxScoreUser("无");
        }
        if(us2!=null){
            ts.setMinScore(us2.getScore());
            ts.setMinScoreUser(us2.getUserName());
        }else{
            ts.setMinScoreUser("无");
        }
        session.setAttribute(startDate+"-"+endDate+"datas1",ts);
        dataMap.put("data",ts);
        return dataMap;
    }

    /**
     * 导出word文档
     *
     * @param startDate
     */
    @RequestMapping(value = "exportWord.action")
    public void exportWord(String startDate, String endDate,HttpSession session, HttpServletResponse response) {
        Map<String, Object> dataMap = new HashMap<>();
        TodayScore datas = (TodayScore) session.getAttribute(startDate+"-"+endDate+"datas1");
        dataMap.put("data", datas);
        String ftlPath = session.getServletContext().getRealPath("/") + "static/ftl";
        String ftlName = "countMonth.ftl";
        String filePath = PropertyUtil.getProperties("file_path") + "/countMonth";
        String fileName = startDate+"~"+endDate + "随车机械师作业情况分析.doc";
        try {
            WordUtil.createWord(dataMap, ftlPath, ftlName, filePath, fileName);
            WordUtil.outputWord(response, fileName, filePath);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
